import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:im_app/im/page/bloc/MessageListCubit.dart';
import 'package:im_app/im/page/model/MessageSendListModel.dart';
import 'package:im_app/im/page/view/model/DataChangeListener.dart';
import 'package:im_app/im/page/view/LoadingView.dart';
import 'package:im_app/im/page/view/component/cell/MessageItemView.dart';
import 'package:im_app/im/page/view/MessageSendView.dart';
import 'package:im_app/im/service/ImSessionService.dart';
import 'package:logger/logger.dart';
import 'package:provider/provider.dart';
import 'package:pull_to_refresh_flutter3/pull_to_refresh_flutter3.dart';
import 'package:scroll_to_index/scroll_to_index.dart';
import '../dao/ImSessionDao.dart';
import '../pojo/Enums.dart';
import '../pojo/ImPojo.dart';
import '../util/ImConstant.dart';
import '../util/ImSingleton.dart';
import 'bloc/SessionSettingCubit.dart';
import 'sub/SessionGroupSettingPage.dart';
import 'sub/SessionUserSettingPage.dart';
import 'bloc/SessionListCubit.dart';

// 未使用
// 消息列表页面+消息发送页面   pull_refresh组件实现
class MessageSendPage2 extends StatelessWidget {
  const MessageSendPage2({super.key});

  @override
  Widget build(BuildContext context) {
    var arguments = ModalRoute.of(context)?.settings.arguments as Map;
    int sessionId = arguments['id'];
    String sessionName = arguments['name'];

    DateTime? currentDay = null;
    if (arguments.containsKey('day')) {
      currentDay = arguments['day'] as DateTime;
    }

    return _MessageSendPageView(sessionId: sessionId, sessionName: sessionName, currentDay: currentDay);
  }
}

class _MessageSendPageView extends StatefulWidget {
  final int sessionId;
  final String sessionName;
  final DateTime? currentDay;

  const _MessageSendPageView({required this.sessionId, required this.sessionName, required this.currentDay, super.key});

  @override
  State<StatefulWidget> createState() => new _MessageSendPageState();
}

class _MessageSendPageState extends DataChangeStateListener<_MessageSendPageView, ImMessage> {
  late AutoScrollController _autoScrollController;
  final RefreshController _refreshController = RefreshController(initialRefresh: false);
  late MessageSendListModel _messageSendListModel;

  // state 变量
  LoadingState _loadingState = LoadingState.loading;

  final _logger = Logger(
    printer: PrettyPrinter(),
  );

  @override
  void initState() {
    super.initState();

    _messageSendListModel = new MessageSendListModel(this, widget.sessionId, widget.currentDay);

    _autoScrollController = AutoScrollController(
        viewportBoundaryGetter: () => Rect.fromLTRB(0, 0, 0, MediaQuery.of(context).padding.bottom),
        axis: Axis.vertical
    );

    ImSingleton.getInstance().messageSendListModel = _messageSendListModel;

    final sessionListCubit = context.read<SessionListCubit>();

    _messageSendListModel.loadData().then((values) {
      setState(() {
        _loadingState = LoadingState.success;
      });

      var sessionDao = ImSessionDao();
      sessionDao.getById(widget.sessionId).then((session) {
        sessionListCubit.changeSession(session!);
      });
    });

    _logger.i("init1 state !!!!!!!!!!!!!!!!!!");
  }

  @override
  void dispose() {
    _autoScrollController.dispose();
    _refreshController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    var messageSendView = MessageSendView(messageSendListModel: this._messageSendListModel);
    return Scaffold(
        appBar: _buildAppBar(context),
        backgroundColor: ImConstant.IM_MAIN_BACKGROUND_COLOR,
        body: LoadingView(
          state: _loadingState,
          child: Column(
            children: [
              Expanded(
                  child: GestureDetector(
                      child: Container(
                        color: ImConstant.IM_MAIN_BACKGROUND_COLOR,
                        child: _buildMessageList(context),
                      ),
                      onTap: () {
                        messageSendView.hideEmoji();
                      })
              ),
              Container(
                decoration: BoxDecoration(
                  color: ImConstant.IM_MAIN_BACKGROUND_COLOR,
                ),
                padding: const EdgeInsets.only(top: 5, bottom: 5),
                child: messageSendView,
              )
            ],
          ),
        )
    );
  }

  Widget _buildMessageList(BuildContext context) {
    return SmartRefresher(
      enablePullDown: true,
      enablePullUp: true,
      header: ClassicHeader(),
      footer: CustomFooter(
        builder: (BuildContext context, LoadStatus? mode) {
          Widget body;
          if (mode == LoadStatus.idle) {
            body = Text("拉取数据");
          } else if (mode == LoadStatus.loading) {
            body = CupertinoActivityIndicator();
          } else if (mode == LoadStatus.failed) {
            body = Text("加载数据失败");
          } else if (mode == LoadStatus.canLoading) {
            body = Text("释放就能加载数据");
          } else {
            body = const Text("无数据");
          }
          return Container(
            height: 55.0,
            child: Center(child: body),
          );
        },
      ),
      controller: _refreshController,
      onRefresh: () async {
        await _messageSendListModel.loadNewsData();
        _refreshController.refreshCompleted();
      },
      onLoading: () async {
        await _messageSendListModel.loadOldData();
        _refreshController.loadComplete();
      },
      child: ListView.builder(
        controller: _autoScrollController,
        scrollDirection: Axis.vertical,
        itemCount: dataList.length,
        // shrinkWrap: true,
        reverse: true,
        itemBuilder: (BuildContext context, int index) {
          var message = dataList.elementAt(index);
          return AutoScrollTag(
              key: ValueKey(index), controller: _autoScrollController, index: index,
              child: MessageItemView(wrapMessage: toWrapImMessage(message)));
        },
      ),
    );
  }

  AppBar _buildAppBar(BuildContext context) {
    var arguments = ModalRoute.of(context)?.settings.arguments as Map;
    return AppBar(
      backgroundColor: ImConstant.IM_MAIN_BACKGROUND_COLOR,
      shape: Border(bottom: BorderSide(color: ImConstant.IM_BORDER_COLOR, width: 1)),
      toolbarHeight: ImConstant.IM_APP_BAR_HEIGTH,
      leading: GestureDetector(
          child: const Padding(
            padding: EdgeInsets.only(left: 0, right: 0),
            child: Icon(Icons.chevron_left, color: ImConstant.IM_TEXT_COLOR),
          ),
          onTap: () {
            ImSingleton.getInstance().cleanUiModel();
            Navigator.of(context).pop();
          }),
      titleSpacing: 5,
      title: Text(
        arguments['name'] ?? "",
        style: const TextStyle(color: ImConstant.IM_TEXT_COLOR),
      ),
      actions: [
        IconButton(
            icon: const Icon(
              Icons.more_horiz,
              color: ImConstant.IM_TEXT_COLOR,
            ),
            onPressed: () async {
              var sessionListCubit = context.read<SessionListCubit>();

              var sessionService = ImSessionService();
              sessionService.getById(widget.sessionId).then((session) {
                Navigator.of(context).push(MaterialPageRoute(
                    builder: (BuildContext context) {
                      return BlocProvider(
                        create: (context) => SessionSettingCubit(session: session!, sessionListCubit: sessionListCubit),
                        child: _buildSettingPage(session!),
                      );
                    },
                    settings: const RouteSettings(name: '/MessageSendPage/Setting')));
              });
            }
        ),
      ],
    );
  }

  Widget _buildSettingPage(ImSession session) {
    if (session!.groupCode == null) {
      return SessionUserSettingPage();
    }
    return SessionGroupSettingPage();
  }
}
